package com.example.springbootdemo.utils;

import com.example.springbootdemo.entity.CloudFileSignDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

/**
 * @ClassName: SignatureUtils
 * @Description: 电子签章
 * @Author: TXW
 * @Date: 2023-07-14
 */

public class SignatureUtils {
//    获取签名
    public static String getSignature(String param, String secret) {
        StringBuilder hash = new StringBuilder();
        byte[] body = param.getBytes(StandardCharsets.UTF_8);
        String sign = "";
        try {
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            hmacSha256.init(secretKey);
            byte[] bytes = hmacSha256.doFinal(body);
            for (byte aByte : bytes) {
                hash.append(Integer.toString((aByte ) + 0x100, 16).substring(1));
            }
            sign = hash.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }

    public static void main(String[] args) throws JsonProcessingException {
        CloudFileSignDTO cloudFileSignDTO = new CloudFileSignDTO();
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(cloudFileSignDTO);
        String url = "https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220309000004/seal-platform/seal/v1/rest/sign/signPdf";
        SignatureUtils.getSignature(s,"8be316c3555f400d907a3dd44fe52f93");

        File file = new File("D:/source/springBootDemo/src/main/resources/static/杭州壹星空摄影有限公司信用承诺2023062019113920230620191140.pdf");
        try {
            String base64String = FileUtils.fileToBase64(file);
            System.out.println(base64String);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
